use crate::{AppError, AppResult, Job, OnlineUser, PageResult, QueryParams, UserStatus};
use chrono::Utc;
use std::collections::HashMap;
use std::sync::Mutex;
use uuid::Uuid;

// 内存中的监控数据存储
lazy_static::lazy_static! {
    static ref ONLINE_USERS: Mutex<HashMap<String, OnlineUser>> = Mutex::new(HashMap::new());
    static ref JOBS: Mutex<HashMap<String, Job>> = Mutex::new(HashMap::new());
}

// 初始化示例在线用户数据
fn init_sample_online_users() {
    let mut online_users = ONLINE_USERS.lock().unwrap();
    
    // 添加示例在线用户
    let sample_users = vec![
        OnlineUser {
            session_id: "session_001".to_string(),
            user_id: "admin".to_string(),
            username: "admin".to_string(),
            nickname: "系统管理员".to_string(),
            ip_address: "192.168.1.100".to_string(),
            login_time: Utc::now() - chrono::Duration::hours(2),
            last_activity: Utc::now() - chrono::Duration::minutes(5),
            user_agent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36".to_string(),
        },
        OnlineUser {
            session_id: "session_002".to_string(),
            user_id: "user_001".to_string(),
            username: "zhangsan".to_string(),
            nickname: "张三".to_string(),
            ip_address: "192.168.1.101".to_string(),
            login_time: Utc::now() - chrono::Duration::hours(1),
            last_activity: Utc::now() - chrono::Duration::minutes(2),
            user_agent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36".to_string(),
        },
        OnlineUser {
            session_id: "session_003".to_string(),
            user_id: "user_002".to_string(),
            username: "lisi".to_string(),
            nickname: "李四".to_string(),
            ip_address: "192.168.1.102".to_string(),
            login_time: Utc::now() - chrono::Duration::minutes(30),
            last_activity: Utc::now() - chrono::Duration::minutes(1),
            user_agent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36".to_string(),
        },
    ];
    
    for user in sample_users {
        online_users.insert(user.session_id.clone(), user);
    }
}

// 初始化示例定时任务数据
fn init_sample_jobs() {
    let mut jobs = JOBS.lock().unwrap();
    
    // 添加示例定时任务
    let sample_jobs = vec![
        Job {
            id: "job_001".to_string(),
            name: "系统日志清理".to_string(),
            job_group: "DEFAULT".to_string(),
            invoke_target: "systemLogCleanTask.cleanLogs()".to_string(),
            cron_expression: "0 0 2 * * ?".to_string(),
            misfire_policy: "DEFAULT".to_string(),
            concurrent: false,
            status: UserStatus::Active,
            create_time: Utc::now() - chrono::Duration::days(30),
            update_time: Utc::now() - chrono::Duration::days(5),
            next_valid_time: Some(Utc::now() + chrono::Duration::hours(10)),
        },
        Job {
            id: "job_002".to_string(),
            name: "SIP注册状态检查".to_string(),
            job_group: "SIP".to_string(),
            invoke_target: "sipRegisterCheckTask.checkRegistrations()".to_string(),
            cron_expression: "0 */5 * * * ?".to_string(),
            misfire_policy: "DEFAULT".to_string(),
            concurrent: true,
            status: UserStatus::Active,
            create_time: Utc::now() - chrono::Duration::days(25),
            update_time: Utc::now() - chrono::Duration::days(3),
            next_valid_time: Some(Utc::now() + chrono::Duration::minutes(3)),
        },
        Job {
            id: "job_003".to_string(),
            name: "通话记录备份".to_string(),
            job_group: "SIP".to_string(),
            invoke_target: "callRecordBackupTask.backupRecords()".to_string(),
            cron_expression: "0 0 1 * * ?".to_string(),
            misfire_policy: "DEFAULT".to_string(),
            concurrent: false,
            status: UserStatus::Inactive,
            create_time: Utc::now() - chrono::Duration::days(20),
            update_time: Utc::now() - chrono::Duration::days(1),
            next_valid_time: Some(Utc::now() + chrono::Duration::hours(13)),
        },
    ];
    
    for job in sample_jobs {
        jobs.insert(job.id.clone(), job);
    }
}

#[tauri::command]
pub async fn get_online_users(params: QueryParams) -> AppResult<PageResult<OnlineUser>> {
    // 初始化示例数据
    init_sample_online_users();
    
    let online_users = ONLINE_USERS.lock().unwrap();
    let mut user_list: Vec<OnlineUser> = online_users.values().cloned().collect();
    
    // 应用过滤条件
    if let Some(keyword) = &params.keyword {
        if !keyword.is_empty() {
            user_list.retain(|user| {
                user.username.contains(keyword) ||
                user.nickname.contains(keyword) ||
                user.ip_address.contains(keyword)
            });
        }
    }
    
    // 分页处理
    let (list, total) = crate::utils::Utils::paginate(
        &user_list,
        params.page,
        params.size,
    );
    
    Ok(PageResult {
        list,
        total,
        page: params.page.unwrap_or(1),
        size: params.size.unwrap_or(10),
    })
}

#[tauri::command]
pub async fn force_logout(session_id: String) -> AppResult<()> {
    let mut online_users = ONLINE_USERS.lock().unwrap();
    
    if online_users.remove(&session_id).is_some() {
        Ok(())
    } else {
        Err(AppError::NotFoundError("会话不存在".to_string()))
    }
}

#[tauri::command]
pub async fn get_online_users_count() -> AppResult<i64> {
    let online_users = ONLINE_USERS.lock().unwrap();
    Ok(online_users.len() as i64)
}

#[tauri::command]
pub async fn get_job_list(params: QueryParams) -> AppResult<PageResult<Job>> {
    // 初始化示例数据
    init_sample_jobs();
    
    let jobs = JOBS.lock().unwrap();
    let mut job_list: Vec<Job> = jobs.values().cloned().collect();
    
    // 应用过滤条件
    if let Some(keyword) = &params.keyword {
        if !keyword.is_empty() {
            job_list.retain(|job| {
                job.name.contains(keyword) ||
                job.job_group.contains(keyword) ||
                job.invoke_target.contains(keyword)
            });
        }
    }
    
    if let Some(status) = &params.status {
        if !status.is_empty() {
            let status_value: i32 = status.parse().unwrap_or(0);
            job_list.retain(|job| {
                let job_status: i32 = job.status.clone().into();
                job_status == status_value
            });
        }
    }
    
    // 分页处理
    let (list, total) = crate::utils::Utils::paginate(
        &job_list,
        params.page,
        params.size,
    );
    
    Ok(PageResult {
        list,
        total,
        page: params.page.unwrap_or(1),
        size: params.size.unwrap_or(10),
    })
}

#[tauri::command]
pub async fn create_job(mut job: Job) -> AppResult<Job> {
    // 验证必填字段
    if job.name.is_empty() {
        return Err(AppError::ValidationError("任务名称不能为空".to_string()));
    }
    
    if job.invoke_target.is_empty() {
        return Err(AppError::ValidationError("调用目标不能为空".to_string()));
    }
    
    if job.cron_expression.is_empty() {
        return Err(AppError::ValidationError("Cron表达式不能为空".to_string()));
    }
    
    // 设置任务ID和时间
    job.id = Uuid::new_v4().to_string();
    job.create_time = Utc::now();
    job.update_time = Utc::now();
    
    // 计算下次执行时间（这里简化处理）
    job.next_valid_time = Some(Utc::now() + chrono::Duration::hours(1));
    
    // 保存任务
    let mut jobs = JOBS.lock().unwrap();
    jobs.insert(job.id.clone(), job.clone());
    
    Ok(job)
}

#[tauri::command]
pub async fn update_job(mut job: Job) -> AppResult<Job> {
    let mut jobs = JOBS.lock().unwrap();
    
    if let Some(existing_job) = jobs.get_mut(&job.id) {
        // 更新字段
        existing_job.name = job.name;
        existing_job.job_group = job.job_group;
        existing_job.invoke_target = job.invoke_target;
        existing_job.cron_expression = job.cron_expression;
        existing_job.misfire_policy = job.misfire_policy;
        existing_job.concurrent = job.concurrent;
        existing_job.status = job.status;
        existing_job.update_time = Utc::now();
        
        // 重新计算下次执行时间
        existing_job.next_valid_time = Some(Utc::now() + chrono::Duration::hours(1));
        
        Ok(existing_job.clone())
    } else {
        Err(AppError::NotFoundError("任务不存在".to_string()))
    }
}

#[tauri::command]
pub async fn delete_job(job_id: String) -> AppResult<()> {
    let mut jobs = JOBS.lock().unwrap();
    
    if jobs.remove(&job_id).is_some() {
        Ok(())
    } else {
        Err(AppError::NotFoundError("任务不存在".to_string()))
    }
}

#[tauri::command]
pub async fn update_job_status(job_id: String, status: i32) -> AppResult<()> {
    let mut jobs = JOBS.lock().unwrap();
    
    if let Some(job) = jobs.get_mut(&job_id) {
        job.status = status.into();
        job.update_time = Utc::now();
        Ok(())
    } else {
        Err(AppError::NotFoundError("任务不存在".to_string()))
    }
}

#[tauri::command]
pub async fn run_job_once(job_id: String) -> AppResult<()> {
    // 这里应该实现实际的任务执行逻辑
    // 目前只是模拟成功
    Ok(())
}

#[tauri::command]
pub async fn pause_job(job_id: String) -> AppResult<()> {
    let mut jobs = JOBS.lock().unwrap();
    
    if let Some(job) = jobs.get_mut(&job_id) {
        job.status = UserStatus::Inactive;
        job.update_time = Utc::now();
        Ok(())
    } else {
        Err(AppError::NotFoundError("任务不存在".to_string()))
    }
}

#[tauri::command]
pub async fn resume_job(job_id: String) -> AppResult<()> {
    let mut jobs = JOBS.lock().unwrap();
    
    if let Some(job) = jobs.get_mut(&job_id) {
        job.status = UserStatus::Active;
        job.update_time = Utc::now();
        Ok(())
    } else {
        Err(AppError::NotFoundError("任务不存在".to_string()))
    }
}

#[tauri::command]
pub async fn get_job_by_id(job_id: String) -> AppResult<Job> {
    let jobs = JOBS.lock().unwrap();
    
    jobs
        .get(&job_id)
        .cloned()
        .ok_or_else(|| AppError::NotFoundError("任务不存在".to_string()))
}

#[tauri::command]
pub async fn get_system_stats() -> AppResult<crate::SystemStats> {
    Ok(crate::utils::Utils::get_system_stats())
}
